package com.tepth.maintenancesystem.view;

import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.tepth.maintenancesystem.R;
import com.tepth.maintenancesystem.SysApplication;
import com.tepth.maintenancesystem.api.HttpClient;
import com.tepth.maintenancesystem.api.MaintainHttp;
import com.tepth.maintenancesystem.bean.Contents;
import com.tepth.maintenancesystem.bean.MaintainListWork;
import com.tepth.maintenancesystem.bean.VehicleMaintain;
import com.tepth.maintenancesystem.presenter.MaintainCompletedLeftAdapter;
import com.tepth.maintenancesystem.presenter.MaintainCompletedRightAdapter;
import com.tepth.maintenancesystem.presenter.MaintainDetailsLeftAdapter;
import com.tepth.maintenancesystem.presenter.MaintainDetailsRightAdapter;
import com.tepth.maintenancesystem.presenter.MaintainDetailsRightOnClick;
import com.tepth.maintenancesystem.untils.AESUtils;
import com.tepth.maintenancesystem.untils.ToastUtils;
import com.tepth.maintenancesystem.untils.Untils;
import com.tepth.maintenancesystem.view.zxingcapture.CaptureActivity;
import com.xiasuhuei321.loadingdialog.view.LoadingDialog;

import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

public class MaintainCompletedActivity extends AppCompatActivity implements MaintainDetailsRightOnClick {

    private MaintainCompletedLeftAdapter leftAdapter;
    private MaintainCompletedRightAdapter rightAdapter;

    private ListView leftListView;
    private ListView rightListView;

    private Context context;

    private ArrayList<MaintainListWork> listCompleted = new ArrayList<>();
    private List<Contents> doingCompleted = new ArrayList<>();//竣检的集合
    private VehicleMaintain obj;
    private LoadingDialog loadingDialog;
    private RelativeLayout rl_completed_barcode, rl_completed_back;
    private TextView tv_completed_title;
    private String name, number;//要提交的作业人的姓名和员工编号
    private int completed_total_count = 0;
    private String dateString;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_maintain_completed);
        SysApplication.getInstance().addActivity(this);
        context = this;
        Bundle bundle = this.getIntent().getBundleExtra("MaintainBundle");
        obj = (VehicleMaintain) bundle.getSerializable("Maintain");
        dateString = this.getIntent().getStringExtra("dateString");

        initView();
        getListWorkContentsNormal();
    }

    private void initView() {
        leftListView = (ListView) findViewById(R.id.left_completed_listview);
        rightListView = (ListView) findViewById(R.id.right_completed_listview);
        rl_completed_barcode = (RelativeLayout) findViewById(R.id.rl_completed_barcode);
        tv_completed_title = (TextView) findViewById(R.id.tv_completed_title);
        rl_completed_back = (RelativeLayout) findViewById(R.id.rl_completed_back);
        tv_completed_title.setText(obj.getVehicleNumber() + "  竣工检验");
        rl_completed_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        rl_completed_barcode.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
//                if (doingCompleted.size() == completed_total_count) {
                    Intent intent = new Intent();
                    intent.setClass(context, NFCDialogActivity.class);
                    startActivityForResult(intent, 1003);
//                }
            }
        });
    }

    private void initLeftListView() {
        leftAdapter = new MaintainCompletedLeftAdapter(this, listCompleted);
        leftAdapter.setSelectPosition(0);
        leftListView.setAdapter(leftAdapter);
        initRightListView(listCompleted.get(0).getListContents());

        leftListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                updataRightListView(position);
            }
        });
    }

    private void updataRightListView(int position) {
        leftAdapter.setSelectPosition(position);
        leftAdapter.notifyDataSetChanged();
        //更新第二ListView
        rightAdapter.setDatas(listCompleted.get(position).getListContents());
        rightAdapter.notifyDataSetChanged();
    }

    private void initRightListView(List<Contents> listContents) {
        rightAdapter = new MaintainCompletedRightAdapter(this, listContents, this);
        rightListView.setAdapter(rightAdapter);
    }

    private void getListWorkContentsNormal() {
        loadingDialog = new LoadingDialog(context);
        loadingDialog.setInterceptBack(false)
                .setLoadingText("正在加载...");
        loadingDialog.show();
        new Thread() {
            @Override
            public void run() {
                listCompleted = MaintainHttp.getListCompleted(context, obj.getId());
                myHandler.sendEmptyMessage(0);
                super.run();
            }
        }.start();
    }

    private Handler myHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 0:
                    loadingDialog.close();
                    if (listCompleted != null) {
                        initLeftListView();
                        for (MaintainListWork work : listCompleted) {
                            completed_total_count += work.getListContents().size();
                        }
                    } else {
                        ToastUtils.showToast(context, "网络错误");
                    }
                    break;
                case 1:
                    loadingDialog.close();
                    String update_code = msg.getData().getString("update_code");
                    if (update_code.equals(HttpClient.SUCCESS)) {
                        ToastUtils.showToast(context, "保存成功");
                        Intent intent = new Intent();
                        intent.setClass(context, MaintainListActivity.class);
                        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                        intent.putExtra("dateString", dateString);
                        startActivity(intent);
                    } else {
                        ToastUtils.showToast(context, "保存失败");
                    }
                    break;
            }
            super.handleMessage(msg);
        }
    };

    @Override
    public void checkboxOnClick(Contents object, int type) {
        int temp = leftAdapter.getCurrentPositionItem().getTemp_select_number();
        switch (type) {
            case 0:
                doingCompleted.add(object);
                leftAdapter.getCurrentPositionItem().setTemp_select_number(temp + 1);
                break;
            case 1:
                doingCompleted.remove(object);
                if (temp > 0) {
                    leftAdapter.getCurrentPositionItem().setTemp_select_number(temp - 1);
                }
                break;
            case 2:
                break;
            case 3:
                break;
        }
        leftAdapter.notifyDataSetChanged();
//        if (doingCompleted.size() == completed_total_count) {
            rl_completed_barcode.setBackgroundColor(Untils.getColor(context, R.color.green_scan_to_barcode_n));
//        } else {
//            rl_completed_barcode.setBackgroundColor(Untils.getColor(context, R.color.grey_scan_to_barcode));
//        }
    }

    @Override
    public void textOnClick(Contents object) {
        String workName = "";
        for (int i = 0; i < listCompleted.size(); i++) {
            if (object.getContentTypeCode().equals(listCompleted.get(i).getContentTypeCode())) {
                workName = listCompleted.get(i).getContentTypeName();
            }
        }
        Intent intent = new Intent();
        Bundle bundle = new Bundle();
        bundle.putParcelable("contents", object);
        bundle.putString("workName", workName);
        bundle.putString("vehicleName", obj.getVehicleNumber());
        intent.putExtra("bundle", bundle);
        if (object.getWorkPersonName().equals("null") || object.getWorkPersonName().equals("")) {
            intent.setClass(context, MaintainWorkDetailsActivity.class);
            startActivityForResult(intent, 1004);
        } else {
            intent.setClass(context, MaintainWorkCompletedDetailsActivity.class);
            startActivity(intent);
        }
    }

    @Override
    public void onActivityResult(final int requestCode, int resultCode, Intent data) {
        if (resultCode == MaintainHttp.BARCODE_RESULTCODE) {
            CharSequence displayContents = data.getCharSequenceExtra("BarCodeContents");
            update(displayContents.toString(), requestCode);
        } else if (resultCode == MaintainHttp.NFC_RESULTCODE) {
            byte[] displayContents = data.getByteArrayExtra("BarCodeContents");
            try {
                update(new String(displayContents, "utf-8"), requestCode);
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else if (requestCode == 1004 && MaintainHttp.RESULT_REFERSHOBJECT == resultCode) {
            Contents obj = data.getBundleExtra("maintainBundle").getParcelable("MaintainObj");
            MaintainListWork leftObj = leftAdapter.getCurrentPositionItem();
            for (int i = 0; i < leftObj.getListContents().size(); i++) {
                Contents rightObjs = leftObj.getListContents().get(i);
                if (obj.getId() == rightObjs.getId()) {
                    rightObjs.setValue(obj.getValue());
                    rightObjs.setRemark(obj.getRemark());

                }
            }
            initRightListView(leftObj.getListContents());
            boolean isContains = false;
            for (Contents content : doingCompleted) {
                if (content.getId() == obj.getId()) {
                    isContains = true;
                    content.setValue(obj.getValue());
                    content.setRemark(obj.getRemark());
                    break;
                }
            }
            if (!isContains) {
                doingCompleted.add(obj);
//                if (doingCompleted.size() == completed_total_count) {
                    rl_completed_barcode.setBackgroundColor(Untils.getColor(context, R.color.green_scan_to_barcode_n));
//                } else {
//                    rl_completed_barcode.setBackgroundColor(Untils.getColor(context, R.color.grey_scan_to_barcode));
//                }
                int temp = leftAdapter.getCurrentPositionItem().getTemp_select_number();
                leftAdapter.getCurrentPositionItem().setTemp_select_number(temp + 1);
                leftAdapter.notifyDataSetChanged();
            }
        }else if(resultCode == MaintainHttp.RETURN_BARCODE){
            Intent intent = new Intent();
            intent.setClass(context, CaptureActivity.class);
            startActivityForResult(intent, requestCode);
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    private void update(String contents, final int requestCode) {
        String result = "";
        try {
            result = AESUtils.code_desEncrypt(contents);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (result == "") {
            ToastUtils.showToast(context, "扫码失败，请重新扫描");
            return;
        }
        String[] results = result.split("_");
        if (result.length() < 2) {
            ToastUtils.showToast(context, "扫码失败，请重新扫描");
            return;
        }
        number = results[0];
        name = results[1];
        loadingDialog = new LoadingDialog(context);
        loadingDialog.setInterceptBack(false)
                .setLoadingText("正在保存...");
        loadingDialog.show();
        new Thread() {
            @Override
            public void run() {
                String result_data = "&workContentsJson=[";
                try {
                    if (requestCode == 1003) {
                        for (int i = 0; i < doingCompleted.size(); i++) {
                            Contents doing = doingCompleted.get(i);
                            JSONObject object = new JSONObject();
                            object.put("Id", doing.getId());
                            object.put("Value", doing.getValue());
                            object.put("WorkPersonCode", number);
                            object.put("WorkPersonName", name);
                            object.put("Remark", doing.getRemark());
                            result_data += object.toString() + ",";
                        }
                        result_data = result_data.substring(0, result_data.length() - 1);
                        result_data += "]&confirmJson=[";
//                            for (int i = 0; i < listCompleted.size(); i++) {
                        MaintainListWork doing = listCompleted.get(0);
                        JSONObject object = new JSONObject();
                        object.put("ContentTypeCode", doing.getContentTypeCode());
                        object.put("ConfirmType", 3);
                        object.put("ConfirmPersonCode", number);
                        object.put("ConfirmPersonName", name);
                        result_data += object.toString() + ",";
//                            }
                        result_data = result_data.substring(0, result_data.length() - 1);
                        result_data += "]";
                        String result_code = MaintainHttp.updateWorkContentsAndConfirm(context, obj.getId(), 2, result_data);
                        Message msg = new Message();
                        Bundle bundle = new Bundle();
                        bundle.putString("update_code", result_code);
                        msg.setData(bundle);
                        msg.what = 1;
                        myHandler.sendMessage(msg);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                super.run();
            }
        }.start();
    }
}
